<template>
    <div class="member animate__animated animate__bounceInLeft">
        <div class="memberTop">
            <el-form class="topfrom" style="width: 100%;" ref="searchFrom" :model="searchInfo">
                <el-form-item label="用户信息" prop="SearchName">
                    <el-input v-model.trim="searchInfo.SearchName" placeholder="请输入用户昵称" />
                </el-form-item>
                <el-form-item label="注册时间" style="width: 300px;" prop="searchTime">
                    <el-date-picker v-model="searchInfo.searchTime" type="datetimerange" start-placeholder="Start Date"
                        end-placeholder="End Date" :default-time="defaultTime1" />
                </el-form-item>
                <el-form-item class="searchButton">
                    <el-button @click="resetFrom(searchFrom)">重置</el-button>
                    <el-button type="primary" @click="dialogVisible = true">添加会员信息</el-button>
                </el-form-item>
            </el-form>
        </div> 
        <!-- 会员信息表格 -->
        <el-table :data="searchKeyWord.slice((currentPage - 1) * pageSize, currentPage * pageSize)" border
            style="width: 100%; margin-bottom: 50px;">
            <el-table-column prop="id" label="编号" width="120" align="center" />
            <el-table-column prop="Meminfo" label="会员昵称" width="180" align="center" />
            <el-table-column prop="MemPrice" label="余额" width="200" align="center" />
            <el-table-column prop="CostPrice" label="消费金额" width="200" align="center" />
            <el-table-column prop="LastTime" label="注册时间" width="230" align="center" />
            <el-table-column prop="RegTime" label="最后登录时间" width="250" align="center" />
            <el-table-column prop="option" label="操作" align="center">
                <template #default="scope">
                    <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
                    <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10, 15, 20]"
            :small="small" :disabled="disabled" :background="background" layout="total, sizes, prev, pager, next, jumper"
            :total="searchKeyWord.length" @size-change="handleSizeChange" @current-change="handleCurrentChange" />

        <!-- 添加会员弹框 -->
        <el-dialog v-model="dialogVisible" title="添加会员信息" width="50%" draggable>
            <el-form ref="ruleFormRef" :model="ruleForm" status-icon :rules="rules" label-width="120px"
                class="demo-ruleForm">
                <el-form-item label="会员信息" prop="Meminfo">
                    <el-input v-model="ruleForm.Meminfo" autocomplete="off" />
                </el-form-item>
                <el-form-item label="余额" prop="MemPrice">
                    <el-input v-model="ruleForm.MemPrice" autocomplete="off" />
                </el-form-item>
                <el-form-item label="消费金额" prop="CostPrice">
                    <el-input v-model.number="ruleForm.CostPrice" />
                </el-form-item>
                <el-form-item label="最后登录时间" prop="LastTime">
                    <el-date-picker v-model="ruleForm.LastTime" type="datetime" placeholder="Pick a Date"
                        format="YYYY/MM/DD hh:mm:ss" value-format="YYYY-MM-DD hh:mm:ss a" />
                </el-form-item>
                <el-form-item label="注册时间" prop="RegTime">
                    <el-date-picker v-model="ruleForm.RegTime" type="datetime" placeholder="Pick a Date"
                        format="YYYY/MM/DD hh:mm:ss" value-format="YYYY-MM-DD hh:mm:ss a" />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="submitForm(ruleFormRef)">
                        确认
                    </el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 会员编辑框 -->
        <MemberEdit @get-new-member-info="getMember"></MemberEdit>
    </div>
</template>

<script setup lang="ts">

import { ref, reactive, onMounted, computed } from 'vue'
import http from '../util/api'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { useStore } from 'vuex'
import MemberEdit from '../components/MemberEdit.vue'

const tableData = ref([])
const dialogVisible = ref(false)
const defaultTime1 = new Date(2000, 1, 1, 12, 0, 0)
const ruleFormRef = ref<FormInstance>()
const searchFrom = ref<FormInstance>()
const store = useStore()

const currentPage = ref(1)
const pageSize = ref(5)
const disabled = ref(false)
const small = ref(false)
const background = ref(false)

const handleSizeChange = (value: number) => {
    pageSize.value = value
}
const handleCurrentChange = (value: number) => {
    currentPage.value = value
}

const ruleForm = reactive<any>({
    Meminfo: '',
    MemPrice: '',
    CostPrice: '',
    LastTime: '',
    RegTime: ''
})

const searchInfo = reactive<any>({
    SearchName: '',
    searchTime: '',
})

const rules = reactive<FormRules>({
    Meminfo: [{ required: true, message: "请输入会员信息", trigger: 'blur' }],
    MemPrice: [{ required: true, message: "请输入会员金额", trigger: 'blur' }],
    CostPrice: [{ required: true, message: "请输入会员消费金额", trigger: 'blur' }],
    LastTime: [{ required: true, message: "请输入会员最后登录时间", trigger: 'blur' }],
    RegTime: [{ required: true, message: "请输入会员注册时间", trigger: 'blur' }],
})

// 获取更新数据
onMounted(() => {
    getMember()
})

// 获取到会员信息
const getMember = () => {
    http("/members", 'get').then((res: any) => {
        console.log(res);
        if (res.status === 200) {
            ElMessage.success('数据更新成功')
            tableData.value = res.data
        }
        else {
            ElMessage.error('数据更新失败')
        }
    })
}

// 增加会员信息
const submitForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validate((valid) => {
        if (valid) {
            let data = {
                'Meminfo': ruleForm.Meminfo,
                'MemPrice': ruleForm.MemPrice,
                'CostPrice': ruleForm.CostPrice,
                'LastTime': ruleForm.LastTime,
                'RegTime': ruleForm.RegTime,
            }
            http("/members", 'POST', data).then((res) => {
                let { data } = res
                if (Object.keys(data).length !== 0) {
                    ElMessage.success('会员信息添加成功')
                } else {
                    ElMessage.error('会员信息添加失败')
                }
                getMember()
            })
            console.log('submit!')
            Object.keys(ruleForm).map(item => {
                delete ruleForm[item]
            })

            dialogVisible.value = false
        } else {
            console.log('error submit!')
            ElMessage.error('输入框不能为空！！！')
            return false
        }
    })
}

// 删除会员信息
const handleDelete = (row: any) => {
    ElMessageBox.confirm(
        '确定要删除该条会员信息吗？删除后信息无法找回，请谨慎删除！！！',
        '删除温馨提示！！！',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
            draggable: true,
        }
    )
        .then(() => {
            http(`/members/${row.id}`, 'delete').then((res: any) => {
                if (res.status === 200) {
                    ElMessage.success('会员信息删除成功')
                }
                else {
                    ElMessage.error('会员信息删除失败')
                }
            })
            getMember()
        })
}

// 重置
const resetFrom = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
    console.log('重置');
}

// 打开编辑框
const handleEdit = (row: any) => {
    store.commit('setDrawer')
    store.commit('editInfo', row)
}

// 查询会员信息
const searchKeyWord = computed(() => {
    console.log("点击成功");
    let newKeyWord: any = []
    for (let i = 0; i < tableData.value.length; i++) {
        if (tableData.value[i].Meminfo.indexOf(searchInfo.SearchName) > -1) {
            newKeyWord.push(tableData.value[i])
        }
    }
    return newKeyWord
})

</script>

<style scoped lang="scss">

.animate__animated .animate__bounceInLeft{
    --animate-duration: 5s;
}
.member {
    width: 100%;
    height: 100%;
    padding: 10px;
    box-sizing: border-box;
    background-color: #fff;

    .memberTop {
        background-color: #fff;
        height: 70px;
        display: flex;
        width: 100%;
        align-items: center;

        .topfrom {
            height: 70px;
            display: flex;
            align-items: center;
            justify-content: space-evenly;

            :deep .el-form-item {
                margin-bottom: 0;
            }

            .el-input {
                width: 200px;
            }

            .el-date-picker {
                width: 200px;
            }
        }
    }
}

</style>